package com.example.application2;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ConnecterActivity extends AppCompatActivity {

    private ListView sy;
    private ContentResolver resolver;
    private SimpleAdapter sa;
    private List<Map<String, Object>> data;
    private List<String> list = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_connecter);
        sy = findViewById(R.id.sy);
        resolver = getContentResolver();
        data = new ArrayList<Map<String, Object>>();
        sa = new SimpleAdapter(this, data, R.layout.siple_list_item, new String[]{"names", "number"}, new int[]{R.id.conName, R.id.text2});
        sy.setAdapter(sa);
    }

    public void all(View view){
        Cursor cursor = resolver.query(Uri.parse("content://com.android.contacts/raw_contacts"), null, null, null, null);
        while (cursor.moveToNext()){
            Map<String, Object> map = new HashMap<>();
            int id = cursor.getInt(cursor.getColumnIndex("_id"));
            String displayName = cursor.getString(cursor.getColumnIndex("display_name"));
            map.put("names", displayName);

            Cursor cursor2 = resolver.query(Uri.parse("content://com.android.contacts/raw_contacts/"+id+"/data"), null, null, null, null);
            while (cursor2.moveToNext()){
                String type = cursor2.getString(cursor2.getColumnIndex("mimetype"));
                if ("vnd.android.cursor.item/phone_v2".equals(type)){
                    String data1 = cursor2.getString(cursor2.getColumnIndex("data1"));
                    map.put("number", data1);
                    Notify(displayName, map);
                }
            }
        }
    }

    public void Notify(String sname, Map<String, Object> map){
        if (!data.isEmpty()){
            for (Map<String, Object> objectMap : data){
                String name = (String) objectMap.get("names");
                list.add(name);
            }
            if (!list.contains(sname)){
                data.add(map);
            } else {
                Toast.makeText(this, sname + "已经在列表中", Toast.LENGTH_LONG).show();
            }
        } else {
            data.add(map);
        }
        sa.notifyDataSetChanged();
    }
}